package com.gjy.sb.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-19 20:33:53
 */
@RestController
@RequestMapping("/tmp")
public class TmpUsageController {

    private static final Logger log = LoggerFactory.getLogger(TmpUsageController.class);

    @RequestMapping("/log")
    public String log(@RequestParam Integer flag) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("ssss");
        }
        if (log.isErrorEnabled()) {
            log.debug("ssss");
        }
        return "1";
    }

    @RequestMapping("/hello")
    public String hello(@RequestParam Integer flag) throws Exception {
        if (flag == 0) {
            return "hello";
        } else if (flag == 1) {
            throw new Exception("ooo");
        } else {
            return String.valueOf(flag);
        }
    }

    private static final Lock lock = new ReentrantLock();
    private static final Lock lock2 = new ReentrantLock();

    @RequestMapping("/lock")
    public void lock() throws Exception {
        new Thread(() -> {
            lock.lock();
            try {
                System.out.println("A");
                TimeUnit.SECONDS.sleep(1);
                try {
                    lock2.lock();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock2.unlock();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }, "A").start();

        new Thread(() -> {
            lock2.lock();
            try {
                System.out.println("B");
                TimeUnit.SECONDS.sleep(1);
                try {
                    lock.lock();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                lock2.unlock();
            }
        }, "B").start();
    }

}
